package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.dto.ConditionVO;
import com.itheima.sfbx.insurance.enums.ConditionEnum;
import com.itheima.sfbx.insurance.mapper.ConditionMapper;
import com.itheima.sfbx.insurance.pojo.CategoryCondition;
import com.itheima.sfbx.insurance.pojo.Condition;
import com.itheima.sfbx.insurance.pojo.InsuranceCondition;
import com.itheima.sfbx.insurance.service.ICategoryConditionService;
import com.itheima.sfbx.insurance.service.IConditionService;
import com.itheima.sfbx.insurance.service.IInsuranceConditionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description：筛选项服务实现类
 */
@Slf4j
@Service
public class ConditionServiceImpl extends ServiceImpl<ConditionMapper, Condition> implements IConditionService {

    @Autowired
    private ICategoryConditionService categoryConditionService;

    @Autowired
    private IInsuranceConditionService insuranceConditionService;

    private LambdaQueryWrapper<Condition> queryWrapper(ConditionVO conditionVO){
        LambdaQueryWrapper<Condition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(conditionVO.getConditionKey()),Condition::getConditionKey,conditionVO.getConditionKey())
                .like(StrUtil.isNotBlank(conditionVO.getConditionKeyName()),Condition::getConditionKeyName,conditionVO.getConditionKeyName())
                .eq(StrUtil.isNotBlank(conditionVO.getDataState()),Condition::getDataState,conditionVO.getDataState());
        return queryWrapper;
    }

    @Override
    public Page<ConditionVO> findPage(ConditionVO conditionVO, int pageNum, int pageSize) {
        //分页查询
        Page<Condition> page = this.page(new Page<>(pageNum, pageSize), queryWrapper(conditionVO));
        return BeanConv.toPage(page, ConditionVO.class);
    }

    @Override
    public ConditionVO findById(String conditionId) {
        //根据id查询
        Condition condition = this.getById(conditionId);
        if(condition==null){
            log.error("不存在该筛选项数据");
            throw new ProjectException(ConditionEnum.FIND_ONE_FAIL);
        }
        return BeanConv.toBean(condition, ConditionVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ConditionVO save(ConditionVO conditionVO) {
        //新增筛选项
        //健壮性判断，key要唯一
        Integer count = this.lambdaQuery()
                .eq(Condition::getConditionKey, conditionVO.getConditionKey())
                .count();
        if(count>0){
            log.error("筛选项key已经存在，key为：{}",conditionVO.getConditionKey());
            throw new ProjectException(ConditionEnum.SAVE_FAIL);
        }
        Condition condition = BeanConv.toBean(conditionVO, Condition.class);
        this.save(condition);
        return BeanConv.toBean(condition, ConditionVO.class);
    }

    @Override
    @Transactional
    public Boolean update(ConditionVO conditionVO) {
        //编辑
        //健壮性判断，判断是否存在该筛选项
        Condition condition = this.getById(conditionVO.getId());
        if(condition==null){
            log.error("不存在该系数项数据,id为：{}",conditionVO.getId());
            throw new ProjectException(ConditionEnum.SAVE_FAIL);
        }
        //判断修改后的key是否唯一,这算一个筛选条件
        Integer count = this.lambdaQuery()
                .eq(Condition::getConditionKey, conditionVO.getConditionKey())
                .ne(Condition::getId, conditionVO.getId())
                .count();
        if (count > 0) {
            log.error("筛选项的key已存在，key为：{}", conditionVO.getConditionKey());
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }
        //判断是否有冗余字段，即是否被其他的表引用，相同数据存在在多个表中
        Integer count1 = categoryConditionService.lambdaQuery()
                .eq(CategoryCondition::getConditionKey, condition.getConditionKey())
                .count();
        Integer count2 = insuranceConditionService.lambdaQuery()
                .eq(InsuranceCondition::getConditionKey, condition.getConditionKey())
                .count();
        if (count1 > 0 || count2 > 0) {
            log.error("筛选项被关联，不能修改，key为：{}",condition.getConditionKey());
            throw new ProjectException(ConditionEnum.UPDATE_FAIL);
        }
        Condition condition1 = BeanConv.toBean(conditionVO, Condition.class);
        return this.updateById(condition1);
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        //删除筛选项
        List<String> ids = Arrays.asList(checkedIds);
        //先把保障项查出来
        List<Condition> conditions = this.listByIds(ids);
        if (CollUtil.isEmpty(conditions)) {
            log.info("筛选项不存在，ids：{}", ids);
            return true;
        }
        Set<String> keys = conditions.stream().map(Condition::getConditionKey).collect(Collectors.toSet());
        Integer count1 = categoryConditionService.lambdaQuery()
                .in(CategoryCondition::getConditionKey, keys)
                .count();
        Integer count2 = insuranceConditionService.lambdaQuery()
                .in(InsuranceCondition::getConditionKey, keys)
                .count();
        if (count1 > 0 || count2 > 0) {
            log.error("存在筛选项被关联，不能删除，keys为：{}", keys);
            throw new ProjectException(ConditionEnum.DEL_FAIL);
        }
        return this.removeByIds(ids);
    }

    @Override
    public List<ConditionVO> findList(ConditionVO conditionVO) {
        //查询集合
        List<Condition> conditions = this.list(queryWrapper(conditionVO));
        if(conditions==null){
            log.error("不存在筛选项集合");
            throw new ProjectException(ConditionEnum.LIST_FAIL);
        }
        return BeanConv.toBeanList(conditions, ConditionVO.class);
    }

    @Override
    public List<ConditionVO> findInConditionKeys(List<String> conditionKeys) {
        //根据conditionkeys查询筛选项数据集合
        List<Condition> conditions = this.lambdaQuery()
                .in(Condition::getConditionKey, conditionKeys)
                .list();
        if(CollUtil.isEmpty(conditions)){
            log.error("不存在筛选项数据,参数为:{}",conditionKeys);
        }
        return BeanConv.toBeanList(conditions,ConditionVO.class);
    }
}
